package com.qw.wx.handler;

import java.util.Map;

import com.xr.util.HttpUtils;
import com.xr.util.JSONUtil;
import com.xr.util.Utils;
import org.springframework.stereotype.Component;

import com.qw.util.WeiXinUtils;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;

/**
 * 转发客户消息给客服Handler
 *
 */
@Component
public class MsgHandler extends AbstractHandler {
  @Override
  public WxMpXmlOutMessage handle(
      WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) 
      throws WxErrorException {
    
    String responseContent = "";
    String wxContent = wxMessage.getContent().trim();
    if (wxContent.equals("1") || wxContent.equals("人脸识别")) {
      responseContent = "请发一张清晰的照片！" + WeiXinUtils.emoji(0x1F4F7);
    } else {
      responseContent = "这就触及到我知识的盲区了";
      try {
        responseContent = HttpUtils.post("http://www.niurenqushi.com/api/simsimi", Utils.newHashMap("txt", wxContent));
        responseContent = JSONUtil.parseMap(responseContent, String.class).get("text");
      } catch (Exception e) {
        logger.error("call chat robot error:", e);
      }
    }
    
    WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(responseContent).fromUser(wxMessage.getToUser())
        .toUser(wxMessage.getFromUser()).build();
    logger.info("MessageHandler:" + m.getContent());
    return m;
  }
}
